package netStudy;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-11-16
 * Time: 8:54
 */
public class TCPEchoClient {
    private Socket socket = null;

    public TCPEchoClient(String serverIP,int serverPort) throws IOException {
        //通过构造方法提前为客户端的Socket存储服务端信息，不同于UDP需要另外设置变量存储
        socket = new Socket(serverIP, serverPort);
    }

    public void start(){
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        //可能会发送多次请求
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream)) {

            while (true) {

                //1.从控制台读取内容
                String requests = scanner.next();

                //2.发送请求
                printWriter.println(requests);

                //刷新缓冲区
                printWriter.flush();

                //3.等待处理响应
                String response = scannerNet.next();

                //4.打印响应内容
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9000);
        client.start();


    }
}
